/* 
Copyright (c) 2008, Feathertail Project

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the Feathertail Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Xml;

using libsecondlife;
using libsecondlife.Capabilities;
using libsecondlife.StructuredData;
using libsecondlife.Packets;

using Feathertail;

namespace Feathertail.Bots
{
    public class NotecardBot : FeathertailBot
    {
        protected LLUUID _NotecardFolder;
        Dictionary<LLUUID, string> _NotecardsInProgress = new Dictionary<LLUUID, string>();

        public NotecardBot(XmlDocument config)
            : base(config)
        {
        }
        
        public override void InitPre()
        {
            _SL.Self.OnInstantMessage += new AgentManager.InstantMessageCallback(Self_OnInstantMessage);

        }


        public override void InitPost()
        {
            base.InitPost();

            _NotecardFolder = _SL.Inventory.FindFolderForType(AssetType.Notecard);
            Console.WriteLine("Notecard Folder: " + _NotecardFolder);

        }

        void Inventory_OnFolderUpdated(LLUUID folderID)
        {
            
        }

        public override void MainLoop()
        {
            bool AllDone = false;
            do
            {
                Console.Write("NotecardBot: ");

                string Cmd = Console.ReadLine();
                switch (Cmd.ToLower())
                {
                    case "exit":
                    case "quit":
                        AllDone = true;
                        break;

                    case "upload":

                        // _SL.Inventory.RequestCreateItem(_NotecardFolder, "Test Notecard", "Description", AssetType.Notecard, InventoryType.Notecard, PermissionMask.All, OnItemCreated);

                        _SL.Assets.OnAssetUploaded += new AssetManager.AssetUploadedCallback(Assets_OnAssetUploaded);
                        AssetNotecard note = new AssetNotecard("Hello World!");
                        LLUUID TransID = _SL.Assets.RequestUpload(note, false, false, true);

                        _SL.Inventory.RequestCreateItem(_NotecardFolder, "Test Card II", "More Description", AssetType.Notecard, TransID, InventoryType.Notecard, PermissionMask.All, OnItemCreated);

                        break;
                }
            } while (!AllDone );

            _SL.Network.Logout();
        }

        void Assets_OnAssetUploaded(AssetUpload upload)
        {
            Console.WriteLine("Uploaded Asset" + upload.AssetID + " :: " + upload.ID + " :: " + upload.Success + " :: " + upload.Type);
        }


        protected void Self_OnInstantMessage(InstantMessage im, Simulator simulator)
        {
            // Only worry about messages from objects and agents, not all the various auto-messages
            if ((im.Dialog == InstantMessageDialog.MessageFromObject)
                || (im.Dialog == InstantMessageDialog.MessageFromAgent))
            {
                Console.WriteLine("=========================");

                // All valid messages will be prefixed with a #
                if( im.Message.StartsWith("#") )
                {
                    // Get the command string
                    string instr = im.Message.Substring(1, im.Message.IndexOf("#", 2)-1);
                    string[] instrParts = instr.Split(new char[] { '|' });
                    string cmd = instrParts[0];

                    // Check if a target for the notecard has been specified
                    LLUUID target = im.FromAgentID;
                    if (instrParts.Length > 1)
                    {
                        LLUUID targetKey = LLUUID.Zero;
                        if (LLUUID.TryParse(instrParts[1], out targetKey))
                        {
                            target = targetKey;
                        }
                    }


                    // If it's exit, then logout.
                    if (cmd.ToLower() == "exit")
                    {
                        if (im.Dialog == InstantMessageDialog.MessageFromAgent)
                        {
                            _SL.Self.InstantMessage(im.FromAgentID, "Logging out");
                        }
                        _SL.Network.Logout();
                    }
                    else
                    {
                        // otherwise the command should be in regards to Starting, Appending to, or Ending a notecard.
                        string body;
                        try
                        {
                            body = im.Message.Substring(im.Message.IndexOf("#", 2) + 1);

                            Console.WriteLine();
                            Console.WriteLine("Command:" + cmd);
                            Console.WriteLine("Target :" + target.ToString());
                            Console.WriteLine("Body   :" + body);

                            // Agent's can't easily specify new lines, so we'll append one by default.
                            if (im.Dialog == InstantMessageDialog.MessageFromAgent)
                            {
                                body = body.Replace("\\n", "\n");
                                body += "\n";
                            }

                            switch (cmd.Substring(0,2).ToLower())
                            {
                                case "sn":
                                    if (im.Dialog == InstantMessageDialog.MessageFromAgent)
                                    {
                                        if (_NotecardsInProgress.ContainsKey(im.FromAgentID))
                                        {
                                            _SL.Self.InstantMessage(im.FromAgentID, "Dropping existing notecard in progress.");
                                        }
                                        _SL.Self.InstantMessage(im.FromAgentID, "Starting new notecard.");
                                    }

                                    _NotecardsInProgress[target] = body;
                                    break;
                                case "en":
                                    if (_NotecardsInProgress.ContainsKey(im.FromAgentID))
                                    {
                                        _NotecardsInProgress[target] += body;
                                    }
                                    else
                                    {
                                        _NotecardsInProgress[target] = body;
                                    }

                                    if (im.Dialog == InstantMessageDialog.MessageFromAgent)
                                    {
                                        _SL.Self.InstantMessage(im.FromAgentID, "Ended notecard, creating and sending.");
                                    }

                                    _SL.Assets.OnAssetUploaded += new AssetManager.AssetUploadedCallback(Assets_OnAssetUploaded);
                                    AssetNotecard note = new AssetNotecard(_NotecardsInProgress[target]);
                                    LLUUID TransID = _SL.Assets.RequestUpload(note, false, false, true);
                                    _SL.Inventory.RequestCreateItem(_NotecardFolder, "NotecardBot Card " + DateTime.Now.ToUniversalTime(), target.ToString(), AssetType.Notecard, TransID, InventoryType.Notecard, PermissionMask.All, OnItemCreated);
                                    break;
                                case "an":
                                    if (_NotecardsInProgress.ContainsKey(im.FromAgentID))
                                    {
                                        _NotecardsInProgress[target] += body;
                                    }
                                    else
                                    {
                                        _NotecardsInProgress[target] = body;
                                    }

                                    if (im.Dialog == InstantMessageDialog.MessageFromAgent)
                                    {
                                        _SL.Self.InstantMessage(im.FromAgentID, "Notecard appended.");
                                    }
                                    break;
                                default:
                                    if (im.Dialog == InstantMessageDialog.MessageFromAgent)
                                    {
                                        _SL.Self.InstantMessage(im.FromAgentID, "Unknown command: " + cmd);
                                    }
                                    break;
                            }

                        }
                        catch (Exception e)
                        {
                            if (im.Dialog == InstantMessageDialog.MessageFromAgent)
                            {
                                _SL.Self.InstantMessage(im.FromAgentID, "Error processing command.");
                            }

                            Console.WriteLine(e.Message);
                            Console.WriteLine(e.StackTrace);

                        }
                    }
                } else if (im.Dialog == InstantMessageDialog.MessageFromAgent)
                {
                    _SL.Self.InstantMessage(im.FromAgentID, "I am a bot and I don't know how to respond to what you said.");
                    Console.WriteLine("IM: " + im.Message);
                }
            }
        }

        protected void OnItemCreated(bool success, InventoryItem item)
        {
            LLUUID Recipient = LLUUID.Zero;
            if( LLUUID.TryParse(item.Description, out Recipient) )
            {
                _SL.Inventory.GiveItem(item.UUID, item.Name, item.AssetType, Recipient, false);

                
            }
        }

        void Assets_OnAssetReceived(AssetDownload transfer, Asset asset)
        {
            Console.WriteLine(Helpers.FieldToUTF8String(asset.AssetData));
        }


    }
}
